package kr.saeildamil.androidstudy.ch19;

import kr.saeildamil.androidstudy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class BackWork extends Activity {
	TextView mResult;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.ch19_backwork);
		setProgressBarIndeterminateVisibility(false);

		mResult = (TextView) findViewById(R.id.ch19_backwork_result);
	}

	public void mOnClick(View v) {
		new BakcWorkAsnycTask().execute(0, 100);

	}

	class BakcWorkAsnycTask extends AsyncTask<Integer, Integer, Integer> {
		boolean mQuit;
		ProgressDialog mProgress;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgress = new ProgressDialog(BackWork.this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("Calculatig");
			mProgress.setMessage("Wait...");
			mProgress.setProgress(0);
			mProgress.setCancelable(false);
			mProgress.setButton("Cancel",
					new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mQuit = true;
					mProgress.dismiss();
				}
			});
			mProgress.show();
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			int result = 0;
			for (int i = params[0]; i < params[1] + 1; i++) {
				result += i;
				publishProgress(result);
				try {Thread.sleep(200);} catch (Exception e) {}
				if(mQuit){
					return result;
			     }
			}
			return result;
		}
		
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
			
		}

		@Override
		protected void onPostExecute(Integer result) {
			Log.d("ddd", "onPostExecute" + result);
			super.onPostExecute(result);
			mResult.setText(result + "");
			mProgress.dismiss();
			mQuit=false;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			mResult.setText("");
			mQuit=true;
		}
	}// end of class AsyncTask
}// end of class BackWorkd
